<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2019/1/4
 * Time: 15:12
 */

namespace app\api\controller;
use think\Loader;
use tixian\WX\Weixin;
use tixian\WX\Ali;

use think\Db;

class Timing
{
    // 微信提现配置
    public $wx_config = [
        'key' => 'wVNAxT3I8dJl1nabp2t6KfNt0ufvurr4', // 商户平台设置的秘钥
        'mch_appid' => 'wx1ddf922fb0cd6ca7', // 商户号的appid
        'mchid' => '1557073621' // 商户号
    ];

    // 支付宝提现配置 rsaPrivateKey:私钥  alipayrsaPublicKey:支付宝生成的支付宝公钥
    public $ali_config = [
        'appId' => '2021001192604261',
        'rsaPrivateKey' => 'MIIEpAIBAAKCAQEAhNJ9Q2PcHxZaFrWF1H0zYUadTxzRmXMAt8VVOkEHShNJVUfKoJ9qPmpWjUxJPPODQoLy9OAYY+mgwY4tEuROeBwJ2Ak4/81pl8suP7DLXf1wKKESEVgYJ2q9BCGqv91ZPTgPhdidn/P5Oq3wf/rLfPvrrkvZ2Gknoq1XcRDZdXqYzd9gml/nXPP/p8QG4xazuA+fIY2mSe6OLFzAV1QeCCgtTx4MmLc27b9WdlF5Os+ubZmOemt6m8u/nnoR8CGucuoQIsQzjwXy256dl/mOrz0QTub5Cwa24ga/wReEut/UVaAWuelMBCyr9ebJhjohnURJ1R/x6uRkxUEH8HX8xQIDAQABAoIBAFZ8gRhKg+CyO0MiO9ybEcO7qV8EUu7qVYNUOSTPhyGS4WNodeaVJycxMt6a1+2aWtQKVI1jBj64t/aQz4THqNjI2RgVGUpnxOQUZy8Nvb6b8lZiW1Nz23Z/KEjyay63wQ393Q24eRrYUGcHL90Fv07I8zPxLA6gmjBxUsjKwe6eT11yv9dk2Z8tu7mDZmh4QXccYqR38rxI6y5FYzOKdDbWB9fvVoUGEydtzJBKa2ynOVexmtOX1/GJsPwPHOsQY3+9I0tz7ksCi3tNIsPyREEqDK9QDsuc6D9dymEeuuSrFFWKr2vUuPsGq/81rQEi7MxlTY7LbPYa9pzk+ElHb1kC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RITDc2KZxkysnFFiCBLTBms8FimzRmylt+tM+ibLG5pUuTY2Vik9k+h79ceSySzE0OFsyNnV1Wi7JxzQfySd9Jjg+VxcjOLQKhJ2LRLCd2QOmRgOFZGvodl/7N/BE03AEzgwieLCC0Owyv7L0W/D3iGmw1It9ZR3fI0FDkDxV/Dxhxy9NWvYlbrtL29PA0CNzQ5hM/ejgPB1QqVC3Cna9wIDAQAB'
    ];
    public function dowload() {//echo 1;die;
        $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
        if(strpos($agent, 'iphone') || strpos($agent, 'ipad'))
        {
            echo 'ios';die;
            echo "<script> location.href='https://itunes.apple.com/cn/app/id1516439349'; </script>";
        }else{
            echo 'Android';die;
            echo "<script> location.href='https://a.app.qq.com/o/simple.jsp?pkgname=com.paixun.fz'; </script>";
        }

    }
    /**
     * 定时消息推送
     */
    public function sendNotice(){
        //未发送的消息列表
        $lists = Db::table('up_notice')
            ->field('n_id, n_time, n_publish_time')
            ->where('n_status', 1)
            ->select();
        $time = date('Y-m-d H:i:s');
        //修改状态
        foreach($lists as $key => $va){
            if($time >= $va['n_publish_time']){//当前时间大于等于设定的时间
                $res = Db::table('up_notice')->where('n_id', $va['n_id'])->setField('n_status', 2);
                $info = Db::table('up_notice')->where('n_id', $va['n_id'])->find();
                if($res){
                    $str = array();
                    if($info['n_type'] ==2){//推送个人
                        $m_ids = explode(',',trim($info['n_user_id'],','));//所有推送的人
                        $list = [];
                        foreach($m_ids as $k => $val){
                            $v = (string)$val;
                            array_push($list, $v);
                        }
                        try{
                            $this->Jpush1(1,$list,$info['n_title'],$str,1);
                        }catch(\Exception $e){

                        }
                    }elseif ($info['n_type'] ==1){//推送全部
                        $list = [];
                        try{
                            $this->Jpush1(2,$list,$info['n_title'],$str,1);
                        }catch(\Exception $e){

                        }
                    }
                }
            }
        }
    }

/**
 * 极光推送--推送消息类型
 * @param $type 1:推送个人  2:推送全体
 * @param $alias 别名 user_id OR token
 * @param $message 推送消息内容
 * @param $code
 * @return array
 */
public function Jpush1($type,$alias,$message,$extras,$code)
{
//        $alias = (string)$alias;
    import('jpush.autoload', EXTEND_PATH);
    //初始化JPushClient
    $client = new \JPush\Client(config('jpush.appKey'),config('jpush.masterSecret'));
    //生成推送Payload构建器
    $push = $client->push();
    //推送平台 'all'  OR  ['ios','android']  OR  'ios','android'
    $push->setPlatform('all');
    //1:推送个人  2:推送全体
    if($type==1){
        $push->addAlias($alias);//按别名推送
    }else{
        $push->addAllAudience();//广播消息推送
    }
    //IOS推送
    $push->iosNotification($message, [
            'alert'=>$message,
            'badge' => '+1',
            'extras' => $extras,
            'sound'=>'default'
        ]
    );
    //Android推送
    $push->androidNotification($message, [
            'alert'=>$message,
            'extras' => $extras
        ]
    );
    $push->message($message, [
        'content_type' => 'text',
        'extras' => [
            'key' => $code
        ]
    ]);
    return $push->send();
}

    /**
     * 通过
     * @return \think\response\Json
     */
        public function adopt(){
            $info = Db::table('up_withdraw')->where('withdraw_status', 2)->find();
            $price = $info['withdraw_money']*0.006 ; // 实际到账金额
            // todo:1 调取微信/支付宝提现接口  2 提现成功修改提现申请状态  3 提现成功参入到order表  4 减用户余额
            if($info['withdraw_type'] == 1){
//                require_once(EXTEND_PATH.'tixian/Weixin.php');
                Loader::import('tixian.Weixin',EXTEND_PATH,'.php');
                $wxtx = new Weixin($this->wx_config);
                $res = $wxtx->wxTiXian($info['withdraw_num'], $info['withdraw_openid'], $price);
                $return_code = (string)$res->return_code;
                $result_code = (string)$res->result_code;
                $return_code = trim(strtoupper($return_code));
                $result_code = trim(strtoupper($result_code));
                if($return_code == 'SUCCESS' && $result_code == 'SUCCESS'){
                    $success = 1;
                }else{
                    $success = 0;
                    $msg = (string)$res->return_msg;
                }
            }else{ // 支付宝
                $data = [
                    'out_biz_no' => $info['withdraw_num'], // 订单号
                    'payee_account' => $info['withdraw_zh'], // 支付宝账号
                    'amount' => $price, // 交易金额
//                'payee_real_name' => $info['withdraw_rel_name'] // 真实姓名
                ];
                Loader::import('tixian.Ali',EXTEND_PATH,'.php');
                $ali = new Ali($this->ali_config);
                $request = $ali->aliTiXian($data);
                if($request['code'] == 1){
                    $success = 1;
                }else{
                    $success = 0;
                    // $result->$responseNode->sub_msg 这个参数 是返回的错误信息
                    $msg = $request['msg'];
                }
            }
            if($success == 1){
                //插入钱包明细
                $result['user_id'] = $info['withdraw_user_id'];
                $result['balance_type'] = $info['withdraw_type'];
                $result['balance_time'] = date('Y-m-d H:i:s');
                if($info['withdraw_type']==1){
                    $result['balance_title'] ="微信提现";
                }elseif ($info['withdraw_type']==2){
                    $result['balance_title'] ="支付宝提现";
                }
                $result['balance_num'] = date('YmdHis') . str_pad(mt_rand(1, 99999999), 4, '0', STR_PAD_LEFT);
                $result['balance_price'] = $info['withdraw_money'];
                $result['balance_status'] = 2;
                $result['balance_jia_jian'] = 1;
                $result['balance_xs'] = 1;
                $result['balance_time'] = date('Y-m-d H:i:s');
                Db::table('up_user_balance')->insertGetId($result);
                Db::startTrans();
                try{
                    // 修改提现订单状态和审核时间
                    Db::table('up_withdraw')
                        ->where('withdraw_id', $info['withdraw_id'])
                        ->update([
                            'withdraw_status' => 4,
                            'withdraw_att_time' => date('Y-m-d H:i:s')
                        ]);
                    Db::commit();
//                    return json(['code' => 200, 'msg' => '操作成功']);
                }catch(\Exception $e){
                    Db::rollback();
//                    return json(['code' => 100, 'msg' => '操作数据库失败']);
                }
            }
//            else{
//                return json(['code' => 100, 'msg' => $msg]);
//            }


    }
}